<script lang="ts" setup>
import { DictData } from "@/store";
import { PropType } from "vue";

defineOptions({
  name: "DictSelect",
});

const props = defineProps({
  modelValue: {
    type: [String, Number],
  },
  placeholder: {
    type: String,
    default: "请选择",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  multiple: {
    type: Boolean,
    default: false,
  },

  // 字典类型
  options: {
    type: Array as PropType<DictData[]>,
    default: () => [],
  },
});

//const
const emit = defineEmits(["update:modelValue"]);

const selectedValue = ref<string | number | []>();

watch(
  [() => props.options, () => props.modelValue],
  ([newOptions, newModelValue]) => {
    if (newOptions.length === 0) return; // 下拉数据源加载未完成不回显
    if (newModelValue == undefined) {
      selectedValue.value = undefined;
      return;
    }
    if (typeof newOptions[0].value === "number") {
      selectedValue.value = Number(newModelValue);
    } else if (typeof newOptions[0].value === "string") {
      selectedValue.value = String(newModelValue);
    } else {
      selectedValue.value = newModelValue;
    }
  }
);

const handleChange = (val?: string | number | []) => {
  emit("update:modelValue", val);
};
</script>

<template>
  <el-select
    v-model="selectedValue"
    :placeholder="placeholder"
    :disabled="disabled"
    :multiple="multiple"
    clearable
    @change="handleChange"
  >
    <el-option
      v-for="option in options"
      :key="option.value"
      :label="option.label"
      :value="option.value"
    />
  </el-select>
</template>
